# @Time: 2023/11/6 16:19
# @Author: Yuanqing He
# @Email: heyuanqing007@163.com
import os

from PyOIMF import ModuleTemp
from PyOIMF.Tools import HttpOperator
from PyOIMF.Tools import FileOperator
from PyOIMF.Tools.DocumentOperator import XMLParsers


class WatershedExtractionModule(ModuleTemp.ModuleTemp):

    def __init__(self):
        super().__init__()
        self.post_param = {}

    def initialize(self):
        # 初始化工作空间
        self.work_space = "./workspace/WatershedExtraction"  # 工作空间地址
        if not os.path.exists(self.work_space):
            os.makedirs(self.work_space)
        self.MSDD = XMLParsers.getDocument(
            "./PyOIMF/ModuleLibrary/WatershedExtraction/ModelServerDescriptionDocument.xml")  # 获取描述文档信息
        super().initialize(self.work_space)
        # 创建FDS模块工作空间和输入数据管理空间
        if not os.path.exists(self.work_space + "/output"):
            os.makedirs(self.work_space + "/output")  # 输出管理空间

    def setData(self, input_data):

        # 配置输入数据
        if len(input_data) < 1:
            print("数据不匹配，请重新配置数据!")
            exit()
        super().setData(input_data)
        input_data_info = XMLParsers.getCollectionByTagName(self.MSDD, "ParamData")
        for index, data_info in enumerate(input_data_info):
            key = XMLParsers.getAttributeByName(data_info, "name")
            value = input_data[index]
            self.post_param[key] = value

    def run(self):
        super().run()
        # 获取模块运行接口
        operation = XMLParsers.getCollectionByTagName(self.MSDD, "Operation")[0]
        operation_url = XMLParsers.getElementValueByElementAndTagNam(operation, "PyOIMF_Node")
        # 模块运行
        HttpOperator.post(str(operation_url).strip(), self.post_param)
        # 获取模块结果数据下载接口
        output_data = XMLParsers.getCollectionByTagName(
            self.MSDD,
            "OutputData")
        file_data = XMLParsers.getCollectionByTagName(output_data[0], "Filedata")
        for data in file_data:
            down_url = XMLParsers.getElementValueByElementAndTagNam(data, "Url")

            # 将下载到工作空间的文件解压，并删除原始压缩包
            if_download = HttpOperator.download_file(down_url, self.work_space + "/output/result.zip")
            if if_download:
                FileOperator.ZipFileUtility.unzip(self.work_space + "/output/result.zip",
                                                  self.work_space + "/output")
                FileOperator.FileUtility.delete_file(self.work_space + "/output/result.zip")
            else:
                print("模拟结果传输失败！")
                return None

    def finish(self):
        super().finish()

    def getStatus(self):
        return super().getStatus()

    def getInputDataInfo(self):
        super().getInputDataInfo()

    def getOutputDataInfo(self):
        super().getOutputDataInfo()

# Press the green button in the gutter to run the script.
# if __name__ == '__main__':
#     print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
